import {
  onShow,
  onHide,
  onPageScroll as _onPageScroll,
  onReachBottom
} from "@dcloudio/uni-app";
import { onMounted, getCurrentInstance } from "vue";
const usePageLifecycle = () => {
  const _this = getCurrentInstance();
  const findPage = (tt) => {
    if (!tt || tt.proxy.mpType === "page")
      return tt;
    return findPage(tt.parent);
  };
  const pageScrollTo = (opt) => {
    uni.pageScrollTo(opt);
  };
  const onPageShow = (hook) => {
    if (!hook)
      return;
    onMounted(() => {
      const page = findPage(_this);
      hook();
      if (Array.isArray(page.onShow)) {
        page.onShow.push(hook);
      } else {
        page.onShow = [hook];
      }
    });
    return;
    onMounted(() => {
      hook && hook();
    });
    onShow(hook);
  };
  const onPageReachBottom = (hook) => {
    if (!hook)
      return;
    onMounted(() => {
      const page = findPage(_this);
      if (Array.isArray(page.onReachBottom)) {
        page.onReachBottom.push(hook);
      } else {
        page.onReachBottom = [hook];
      }
    });
    return;
    onReachBottom(hook);
  };
  const onPageScroll = (hook) => {
    if (!hook)
      return;
    onMounted(() => {
      const page = findPage(_this);
      if (Array.isArray(page.onPageScroll)) {
        page.onPageScroll.push(hook);
      } else {
        page.onPageScroll = [hook];
      }
    });
    return;
    _onPageScroll(hook);
  };
  return {
    onPageShow,
    onPageHide: onHide,
    /**
     * 目前在组件中使用该hook时，需要页面onPageScroll有值才会触发。
     * 简单粗暴的办法是全局给mixin一个空函数（支付宝小程序必须加载页面，加全局mixin无效）
     */
    onPageScroll,
    onPageReachBottom,
    pageScrollTo
  };
};
export {
  usePageLifecycle
};
